﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.DependencyInjection;
using WoodAdmin.Common.Helper.Net;
using System.Linq;

namespace WoodAdmin.Common.Extention
{
    /// <summary>
    /// HttpContext扩展
    /// </summary>
    public static class HttpContextExtensions
    {
        public static void AddHttpContextHelperAccessor(this IServiceCollection services)
        {
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        }

        public static IApplicationBuilder UseHttpContextHelper(this IApplicationBuilder app)
        {
            var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
            HttpContextHelper.Configure(httpContextAccessor);
            return app;
        }

		/// <summary>
		/// 获取验证消息提示并格式化提示
		/// </summary>
		public static string GetValidationSummary(this ModelStateDictionary modelState, string separator = "\r\n")
		{
			if (modelState.IsValid) return null;

			//var error = new StringBuilder();

			foreach (var item in modelState)
			{
				var state = item.Value;
				var message = state.Errors.FirstOrDefault(p => !string.IsNullOrWhiteSpace(p.ErrorMessage))?.ErrorMessage;
				if (string.IsNullOrWhiteSpace(message))
				{
					message = state.Errors.FirstOrDefault(o => o.Exception != null)?.Exception.Message;
				}
				if (string.IsNullOrWhiteSpace(message)) continue;
				return message;
				//if (error.Length > 0)
				//{
				//	error.Append(separator);
				//}
				//error.Append(message);
			}
			//return error.ToString();
			return string.Empty;
		}
	}
}
